package com.opdar.seed.idoc.services;

import com.opdar.framework.db.impl.BaseWhere;
import com.opdar.framework.db.interfaces.IDao;
import com.opdar.framework.db.interfaces.IDatabase;
import com.opdar.framework.web.SeedWeb;
import com.opdar.framework.web.anotations.Component;
import com.opdar.framework.web.anotations.Inject;
import com.opdar.framework.web.common.Context;
import com.opdar.seed.extra.utils.StringUtils;
import com.opdar.seed.idoc.base.JSONParser;
import com.opdar.seed.idoc.beans.HeaderEntity;
import com.opdar.seed.idoc.beans.InterfaceEntity;
import com.opdar.seed.idoc.beans.ParamEntity;
import sun.misc.BASE64Encoder;

import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by 俊帆 on 2015/8/21.
 */
@Component
public class InterfaceService {

    @Inject
    IDatabase database;

    @Inject
    JSONParser parser;

    public List<InterfaceEntity> findInterfaceWithProject(String projectId) {
        IDao<InterfaceEntity> interfaceDao = database.getDao(InterfaceEntity.class);
        List<InterfaceEntity> interfaces = interfaceDao.select().where("project_id", projectId).ORDERBY((BaseWhere.Order) Context.get("createTimeDesc")).WhereEND().end().findAll();
        return interfaces;
    }


    public Integer findInterfaceCountWithProject(String projectId) {
        IDao<InterfaceEntity> interfaceDao = database.getDao(InterfaceEntity.class);
        Integer interfaceCount = interfaceDao.count().where("project_id", projectId).WhereEND().end(Integer.class).findOne();
        return interfaceCount;
    }

    public boolean insert(InterfaceEntity inter) {
        IDao<InterfaceEntity> interfaceDao = database.getDao(InterfaceEntity.class);
        inter.setId(UUID.randomUUID().toString());
        return interfaceDao.insert(inter).end().status() > 0;
    }

    public InterfaceEntity save(InterfaceEntity inter) {
        IDao<InterfaceEntity> interfaceDao = database.getDao(InterfaceEntity.class);
        if(StringUtils.isBlank(inter.getHeaders())){
            inter.setHeaders("");
        }
        if(StringUtils.isBlank(inter.getPostParams())){
            inter.setPostParams("");
        }
        if(StringUtils.isBlank(inter.getBody())){
            inter.setBody("");
        }
        if(StringUtils.isBlank(inter.getResult())){
            inter.setResult("");
        }
        if(StringUtils.isBlank(inter.getUrl())){
            inter.setUrl("");
        }
        if(StringUtils.isBlank(inter.getQueryString())){
            inter.setQueryString("");
        }
        if(StringUtils.isBlank(inter.getInterfaceName())){
            inter.setInterfaceName("(无名称)");
        }

        InterfaceEntity interfaceEntity = null;
        inter.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        if (StringUtils.isBlank(inter.getId())) {
            String projectId = (String) SeedWeb.SharedRequest().get().getSession().getValue("projectId");
            inter.setProjectId(projectId);
            inter.setId(UUID.randomUUID().toString());
            inter.setCreateTime(new Timestamp(System.currentTimeMillis()));
            //insert
            interfaceDao.insert(inter).end();
        } else {
            //update
            interfaceDao.update(inter).where("id", inter.getId()).WhereEND().end();
        }
        interfaceEntity = findById(inter.getId());
        return interfaceEntity;
    }

    public InterfaceEntity findById(String id) {
        IDao<InterfaceEntity> interfaceDao = database.getDao(InterfaceEntity.class);
        return interfaceDao.select().where("id", id).WhereEND().end().findOne();
    }

    public boolean remove(String id) {
        IDao<InterfaceEntity> interfaceDao = database.getDao(InterfaceEntity.class);
        return interfaceDao.delete().where("id", id).WhereEND().end().status() > 0;
    }

    public void create(String id, Map<String, Object> dataModel) {
        InterfaceEntity entity;
        if (!StringUtils.isBlank(id)) {
            entity = findById(id);
            dataModel.put("id", entity.getId());
            dataModel.put("body", entity.getBody());
            dataModel.put("alias", entity.getInterfaceName());
            String url = entity.getUrl();
            if (!StringUtils.isBlank(entity.getQueryString())) {
                url += "?" + entity.getQueryString();
            }
            dataModel.put("url", url);
            if (!StringUtils.isBlank(entity.getHeaders())) {
                List<HeaderEntity> headers = parser.parseArray(entity.getHeaders(), HeaderEntity.class);
                dataModel.put("headers", headers);
            }
            if (!StringUtils.isBlank(entity.getPostParams())) {
                List<ParamEntity> params = parser.parseArray(entity.getPostParams(), ParamEntity.class);
                dataModel.put("params", params);
            }
        }
        if (!dataModel.containsKey("headers")) {
            List<HeaderEntity> headers = new LinkedList<HeaderEntity>();
            headers.add(new HeaderEntity("Content-Type", "application/x-www-form-urlencoded"));
            dataModel.put("headers", headers);
        }
    }

    public boolean updateResultById(byte[] result, String id) {
        IDao<InterfaceEntity> interfaceDao = database.getDao(InterfaceEntity.class);
        BASE64Encoder encoder = new BASE64Encoder();
        String b64 = encoder.encode(result);
        InterfaceEntity entity = new InterfaceEntity();
        entity.setResult(b64);
        return interfaceDao.update(entity).where("id", id).WhereEND().end().status() > 0;
    }
}
